package org.example;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpServer {
    //静态资源路径
    public static final String WEB_ROOT=
            System.getProperty("user.dir")+ File.separator+"webroot";
    //监听的客户端端口
    public static final int port=8080;
    //关闭路径
    private static final String SHUTDOWN_COMMAND="/SHUTDOWN";
    private boolean shutdown=false;

    public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
        HttpServer httpServer = new HttpServer();
        httpServer.await();
    }
    //等待客户端连接
    public void await() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
        //创建ServerSocket
        ServerSocket serverSocket=new ServerSocket(port);
        while(!shutdown){//循环监听客户端请求
            Socket socket= serverSocket.accept();
            //获取socket的输入流输出流
            InputStream inputStream= socket.getInputStream();
            OutputStream outputStream= socket.getOutputStream();
            //创建request对象
            MyHttpRequest myHttpRequest = new MyHttpRequest(inputStream,socket);
            //调用解析方法
            myHttpRequest.parse();
            if(myHttpRequest.getUri().endsWith("jsp")){
                //需要判断jsp文件是否存在
                String uri = myHttpRequest.getUri();
                File file = new File(HttpServer.WEB_ROOT,uri);
                if(!file.exists()){
                    //文件不存在返回404
                    String errorMessage="HTTP/1.1 404 File Not Found\r\n"
                            +"Content-Type: text/html\r\n"
                            +"Content-Length: 23\r\n"
                            +"\r\n"
                            +"<h1>File Not Found</h1>";
                    //响应数据
                    outputStream.write(errorMessage.getBytes());
                }else{
                    //获取jsp文件名
                    int index1=uri.lastIndexOf("/");
                    int index2=uri.indexOf(".",index1);
                    String jspName=uri.substring(index1+1,index2);
                    //创建响应对象
                    MyHttpResponse myHttpResponse = new MyHttpResponse(myHttpRequest, socket);
                    //调用ClassLoadProcessor进行class文件加载执行
                    ClassLoadProcessor.loadClass(jspName,myHttpRequest,myHttpResponse);
                    //调用resp的complete方法进行响应
                    myHttpResponse.complete();
                }
                //关闭socket
                socket.close();
                //判断是否退出监听
                shutdown=myHttpRequest.getUri().equals(SHUTDOWN_COMMAND);

            }

        }

    }

}
